package it.fuzzylogics.fuzzywidgetsLibrary.client.FuzzyImageBox;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.LoadListener;
import com.google.gwt.user.client.ui.Widget;


public class FImageBox extends AbsolutePanel {
    public Image img;
    String url = null;
    int width, height;


    public FImageBox() {

        img = new Image();

        add(img);
        img.addLoadListener(new LoadListener() {

            public void onError(Widget sender) {
             
            }


            public void onLoad(Widget sender) {

                if (img.getUrl().equals(""))
                    return;
                
                if (img.getWidth() > 0 && img.getHeight() > 0)
                    adjustImage(width, height, img.getWidth(), img.getHeight());


            }
        });


    }

    public String getUrl() {
        return url;
    }

    public void setUrl(final String url) {

        this.url = url;
        loadImage(width, height);
    }

    private void loadImage(final int w, final int h) {

        if (w == 0 && h == 0) return;

        img.setWidth("");
        img.setHeight("");

        img.setUrl(url);
    }

    private void adjustImage(int w, int h, int imgW, int imgH) {
        if (imgW <= w && imgH <= h) {
            upResizeImage(w, h, imgW, imgH);
        } else {
            downResizeImage(w, h, imgW, imgH);
        }
    }


    private void downResizeImage(int w, int h, int imgW, int imgH) {

        double scale = 1;
        int ww;
        int hh;

        ww = imgW;

        do {
            ww = (int) (imgW / scale);
            hh = (int) (imgH / scale);

            scale += 0.05;
        } while (!(ww <= w && hh <= h));


        setWidgetPosition(img, (w - ww) / 2, (h - hh) / 2);
        img.setPixelSize(ww, hh);
    }


    private void upResizeImage(int w, int h, int imgW, int imgH) {
        double scale = 1;

        int ww;
        int hh;

        do {
            ww = (int) (imgW * scale);
            hh = (int) (imgH * scale);


            scale += 0.05;
        } while (!(ww >= w / 1.1 || hh >= h / 1.1));


        setWidgetPosition(img, (w - ww) / 2, (h - hh) / 2);
        img.setPixelSize(ww, hh);
    }


    public void setPixelSize(int w, int h) {

        super.setPixelSize(w, h);

        width = w;
        height = h;
        loadImage(w, h);
    }

    public void onLoad() {

        super.onLoad();

        loadImage(width, height);


    }
}
